import java.util.concurrent.atomic.AtomicInteger;

/**
 * 不保证原子性
 * 用原子类解决
 */
public class Atomic {
    // private static volatile int sum = 0;
    private static AtomicInteger sum = new AtomicInteger(0);

    public static void main(String[] args) {
        new Thread(() -> {
            for (int i = 0; i < 1000000; i++) {
                // sum++;
                sum.incrementAndGet();
            }
            ;
        }).start();
        new Thread(() -> {
            for (int i = 0; i < 1000000; i++) {
                // sum++;
                sum.incrementAndGet();
            }
            ;
        }).start();
        while (Thread.activeCount() > 1) {
            Thread.yield();
        }
        System.out.println(sum);
    }
}
